import numpy
import math
 
def SMA( data, lag, weights = [] ):
    ''' simple (weighed) moving average '''
        
    x = data[0]
    y = data[1]
        
    if not any(weights):
        weights = numpy.ones( lag ) / float(lag)
        
    if len(y) >= lag:
        # we will ignore the boundary values here, so we set mode = valid
        sma_y = numpy.convolve( y, weights, mode = 'valid' )
        return numpy.vstack(( x[lag-1:], sma_y ))
    else:
        return numpy.array([])
       
def EMA( data, lag ):
    ''' exponential moving average '''
    
    multiplier = 2.0 / (1 + lag)
    weights = numpy.exp( numpy.arange(lag)*(math.log(multiplier)) )
    weights = weights / weights.sum()
    
    if len(data[0]) >= lag:
        return SMA( data, lag, weights )
    else:
        return numpy.array([])
        
def MACD( data, L, S, D ):
    ''' 
        MACD Line: (S-day EMA - L-day EMA) 
        Signal Line: D-day EMA of MACD Line
    '''
    
    lema = EMA( data, L )
    sema = EMA( data, S )
    
    macd_line = sema[1][(L-S):] - lema[1]
        
    return macd_line
    
       
       
    
